package org.andao.core.utils;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

/**
 * 获取HttpServlet的Wrapper.
 *
 * @author Seewo Software - Marco.hu(huzhiguo@cvte.cn)
 *
 */
public class WrappedRequest extends HttpServletRequestWrapper{

	private final String body;	
	
	/**
	 * 转换HttpServletRequest >> WrappedRequest.
	 * @param request
	 * @return
	 * @throws IOException
	 */
    public static WrappedRequest wrap(final HttpServletRequest request) throws IOException {
        if (request instanceof WrappedRequest) {
            return (WrappedRequest) request;
        }

        return new WrappedRequest(request);
    }
    
    /**
     * 转换body-->byte stream.
     */
    @Override
    public ServletInputStream getInputStream() throws IOException {
        return new ServletInputStream() {
            final ByteArrayInputStream inputStream = new ByteArrayInputStream(body.getBytes());

            public int read() throws IOException {
                return inputStream.read();
            }
        };
    }

    public String getBody() {
        return body;
    }
	
	public WrappedRequest(final HttpServletRequest request) throws IOException {
		super(request);	
		//获取body,转为String
		StringBuilder stringBuilder = new StringBuilder();
		BufferedReader bufferedReader = null;
		InputStream in = null;
		try {
			in = request.getInputStream();
		    if (in != null) {
		        bufferedReader = new BufferedReader(new InputStreamReader(in));
		        char[] charBuffer = new char[128];
		        int bytesRead = -1;
		        while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
		            stringBuilder.append(charBuffer, 0, bytesRead);
		        }
		    } else {
		        stringBuilder.append("");
		    }
		    } catch (IOException ex) {
		        throw ex;
		    } finally {
		        if(null != in){
		            in.close();
		        }
		        if (null != bufferedReader) {
		            bufferedReader.close();
		        }
		   }		
		   body = stringBuilder.toString();        
	}

}
